<?php

namespace app\index\controller;

use app\BaseController;
use app\index\model\ArtAdopt;
use app\index\model\Article as ModelArticle;
use app\index\model\Category;
use app\index\model\Collect;
use app\index\model\Comment;
use app\index\model\PayedArt;
use app\index\model\Tap;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Session;

class Article extends BaseController
{
    protected $middleware = ['isLogin' => ['except' => ['index', 'search']]];

    public function index()
    {
        $this->logs('文章首页');
        $param = input();
        $art_id = @$param['art_id'];
        if ($art_id == '') return view('error/404', ['msg' => '缺少文章Id']);
        $data = (new ModelArticle())->getArticleData($art_id);
        
        if (!$data) return view('error/404', ['msg' => '该文章已丢失']);
        // 管理员可以正常 预览未审核文章
        if (!Session::has('admin')) {
            if ($data->status == 0) {
                // 未登录用户 | 已登录用户（非文章发布者)
                if (!Session::has('user') || Session::get('user.user_id') != $data->user_id) {
                    return view('error/404', ['msg' => '该文章正在审核中...']);
                }
            }
        }
        Db::name('article')->where('id', $art_id)->inc('heat')->update();
        $commentList = (new Comment())->list(['article_id' => $art_id]);
        $page = $commentList['list']->render();
        $data = (new ModelArticle)->readDataHandel($art_id, $data);
        return view('index', ['data' => $data, 'list' => $commentList, 'page' => $page]);
    }
    // 个人中心数据
    public function list()
    {
        $this->logs('文章列表（接口）');
        $art = (new ModelArticle())->list(['user_id' => $this->user['user_id']]);
        return json($art);
    }

    public function search()
    {
        $this->logs('文章搜索');
        $param = input();
        if (!isset($param['key'])) return error('请输入关键词');
        $key = $param['key'];
        $artModel = new ModelArticle();
        $list =  $artModel::where('title', 'like', '%' . $key . '%')->where('status',1)->order('is_top desc,is_hot desc,id desc ,sort asc')->paginate(10);
        // 得到其他的属性 ， 提交list
        $list =  $artModel->list(['list' => $list]);
        $page = $list['list']->render();
        return view('search', ['list' => $list, 'key' => $key, 'page' => $page]);
    }
    public function add()
    {
        $this->logs('添加文章视图');
        $categoryList = (new Category())->list();
        $tapList = (new Tap())->list();
        $cid = input('cid');
        if (empty($cid)) return error('cid不能为空');
        $categoryList = (new Category)->threeChild($cid);
        if (!$categoryList) {
            return view('error/404', ['msg' => '当前分类下暂无板块哦！']);
        }
        // 生成随机sign，防止用户抓到批量提交
        Session::set('art_sign', randStr());
        return view('add', ['categoryList' => $categoryList, 'tapList' => $tapList]);
    }
    // 文章介绍图
    public function uploadImg()
    {
        $this->logs('文章介绍图上传');
        $images = request()->file('img_path');
        if (!empty($images)) {
            $path = Filesystem::disk('images')->putFile('article', $images);
            // request()->domain() . 
            $path = str_replace('\\', '/', $path);
            $path = "/static/images/" . $path;
            $data = [
                "errno" => 0,
                'data' => [
                    'url' => $path,
                    'alt' => $path,
                    'href' => $path,
                ]
            ];
            return json($data);
        }
    }

    public function doAdd()
    {
        $this->logs('添加文章');
        if (request()->isPost()) {
            if (!Session::has('art_sign')) return json(error(error('缺少sign值')));
            if (input('sign') != Session::get('art_sign')) return error('sign过期或不存在,请尝试刷新该网页');
            $param = input();
            // 判断需要 ，判断是否为悬赏文章3 是添加时不需要改参数，更改时才需要
            if (array_key_exists('id', $param)) unset($param['id']);
            $data = ModelArticle::handleParam($param);
            if (is_array($data)) {
                if (array_key_exists('comType', $data)) {
                    $comType = $data['comType'];
                    unset($data['comType']);
                }
                $res = ModelArticle::create($data);
                if ($res) {
                    if ($data['type'] == 3) {
                        ArtAdopt::create(['author_id' => Session::get('user.user_id'), 'type' => $comType, 'article_id' => $res->id]);
                    }
                    Session::set('art_sign', '');
                    return success();
                }
                return error('发布失败');
            }
            return error($data);
        }
    }
    public function update()
    {
        $this->logs('更新文章视图');
        Session::set('art_sign', randStr());
        $art_id = input('art_id');
        if ($art_id == '') return view('error/404', ['msg' => '文章ID不能为空']);
        $isUserArt = ModelArticle::where(['user_id' => $this->user['user_id'], 'id' => $art_id]);
        if ($isUserArt->findOrEmpty()->isEmpty()) return view('error/404', ['msg' => '文章不存在']);
        else {
            $data = $isUserArt->find();
            if ($data->type == 3) {
                $adopt = ArtAdopt::where('article_id', $art_id)->find();
                if ($adopt) {
                    $data['comType'] = $adopt->type;
                }
            }
            // 三级分类
            $catePid = Category::find($data->category_id);
            // 二级分类
            $twoPid = Category::find($catePid->pid);
            // 父分类
            $parCate = Category::find($twoPid->pid);
            // $parentCate = '['.$parCate->category.']' ."  >>  " . '['.$twoPid->category.']';
            $parentCate = $parCate->category . "   >>   " . $twoPid->category;
            $categoryList = (new Category)->threeChild($catePid->pid);
            $tapList = (new Tap())->list();
            return view('update', ['data' => $data, 'categoryList' => $categoryList, 'tapList' => $tapList, 'parentCate' => $parentCate]);
        }
    }
    public function doUpdate()
    {
        $this->logs('更新文章');
        if (Request()->isPost()) {
            if (!Session::has('art_sign')) return json(error(error('缺少sign值')));
            if (input('sign') != Session::get('art_sign')) return error('sign过期或不存在,请尝试刷新该网页');
            $param = input();
            $art_id = @$param['id'];
            if (!ModelArticle::where(['user_id' => $this->user['user_id'], 'id' => $art_id])->findOrEmpty()->isEmpty()) {
                $data = ModelArticle::handleParam($param);
                if (!is_array($data)) return error($data);
                if (array_key_exists('comType', $data)) {
                    $comType = $data['comType'];
                    unset($data['comType']);
                }
                $data['update_uid'] = $this->user['user_id'];
                // 默认采用的评论显示方式为全局可看
                $adopt = 1;
                if ($data['type'] == 3) {
                    $adopt = ArtAdopt::where('article_id', $art_id)->update(['type' => $comType]);
                }
                $res = ModelArticle::where('id', $art_id)->update($data);
                if ($res || $adopt) {
                    Session::set('art_sign', '');
                    return success();
                } else return error();
            }
        }
    }
    public function del($art_id)
    {
        $this->logs('删除文章');
        $res = (new ModelArticle())->del($art_id);
        if ($res == 1) return success();
        return error();
    }
    // 采纳某人的答案
    public function adopt()
    {
        $this->logs('采纳答案');
        $art_id = input('art_id');
        $cid = input('cid');
        if(empty($art_id) || empty($cid)) return error('缺少必要参数');
        $Comment = Comment::find($cid);
        $uid = $Comment->user_id;
        if($uid == Session::get('user.user_id')) return error('操作错误');
        $art_id = $Comment->article_id;
        $res = ArtAdopt::adopt($art_id, $uid , $cid);
        if ($res == 1) return success();
        else return error($res);
    }
     // 付费文章支付
     public function pay()
     {
         $this->logs('文章付费');
         $art_id = input('art_id');
         $hasArt = ModelArticle::where('id', $art_id);
         if (!$hasArt->findOrEmpty()->isEmpty()) {
             $type = $hasArt->value('type');
             if ($type != 2) return error('文章类型与请求不符');
             $uid = Session::get('user.user_id');
             $isPay = PayedArt::where(['user_id' => $uid, 'article_id' => $art_id])->findOrEmpty()->isEmpty();
             if ($isPay) {
                 $res =  PayedArt::pay($art_id);
                 if($res != 1) return error($res);
                 return success();
             }
         }
     }
}
